import type { ConsultOrderItem, FollowType } from '@/types/consult.d'
import {
  cancelOrder,
  deleteOrder,
  followOrUnFollow,
  getPrescriptionPic
} from '@/services/consult'
import { onMounted, onUnmounted, ref, type Ref } from 'vue'
import { showImagePreview, showToast, type FormInstance } from 'vant'
import { OrderType } from '@/enum'
import type { OrderDetail } from '@/types/order'
import { getMedicalOrderDetail } from '@/services/order'
import { sendMobileCode } from '@/services/user'
import type { CodeType } from '@/types/user'

// 1. 关注和取消关注业务函数
export const useFollow = (type: FollowType) => {
  const loading = ref(false)
  // {a, b} 类型，传值得时候 {a, b, c} 也可以，这是类型兼容：多的可以给少的
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    // 1.1 设置加载状态
    loading.value = true
    // 1.2 调用接口
    try {
      await followOrUnFollow({ id: item.id, type })
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      loading.value = false
    }
  }
  return { loading, follow }
}

// 2. 查看处方
export const useShowPrescription = () => {
  const getPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      showImagePreview([res.data.url])
    }
  }
  return { getPrescription }
}

// 3. 取消订单
export const useCancelOrder = () => {
  const loading = ref(false)
  const cancelConsultOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await cancelOrder(item.id)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showToast('取消订单成功')
    } catch (error) {
      showToast('取消订单失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, cancelConsultOrder }
}

// 4. 删除订单
export const useDeleteOrder = (cb: () => void) => {
  const deleteLoading = ref(false)
  const deleteConsultOrder = async (item: ConsultOrderItem) => {
    deleteLoading.value = true
    try {
      await deleteOrder(item.id)
      // 执行函数, 函数内部处理什么业务取决于使用hook函数的地方
      cb && cb()
      showToast('删除订单成功')
    } catch (error) {
      showToast('删除订单失败')
    } finally {
      deleteLoading.value = false
    }
  }
  return { deleteLoading, deleteConsultOrder }
}

// 5. 封装获取药品订单详情
export const useOrderDetail = (id: string) => {
  const order = ref<OrderDetail>()
  const loading = ref(false)
  onMounted(async () => {
    try {
      loading.value = true
      const res = await getMedicalOrderDetail(id)
      order.value = res.data
      loading.value = false
    } catch (error) {
      loading.value = false
    }
  })
  return { loading, order }
}

// 6. 发送短信验证码
export const useSendMobileCode = (
  mobile: Ref<string>,
  type: CodeType = 'login'
) => {
  const time = ref(0)
  const formRef = ref<FormInstance>()
  let timerId: number
  const send = async () => {
    // 3.1 如果倒计时>0, 则不能获取验证码
    if (time.value > 0) return
    // 3.2 调用表单的校验方法校验手机号
    await formRef.value?.validate('mobile')
    // 3.3 调用获取短信验证码接口
    const res = await sendMobileCode(mobile.value, type)
    showToast(`短信验证码是: ${res.data.code}`)

    // 3.4 开启倒计时
    time.value = 60
    window.clearInterval(timerId)
    timerId = window.setInterval(() => {
      time.value--
      if (time.value <= 0) window.clearInterval(timerId)
    }, 1000)
  }

  onUnmounted(() => {
    window.clearInterval(timerId)
  })

  return { formRef, time, send }
}
